# -*- coding: utf-8 -*-
# coding=utf-8
import json

from collections import defaultdict
from utils.log import logger


class MeasureTypeRecognition:
    def __init__(self, data_dict_path):
        """
        根据数据字典路径，读取数据字典，构造measure类型字典
        :param data_dict_path: 数据字典路径
        """
        try:
            self.measure_dict = defaultdict(bool)
            with open(data_dict_path, 'r', encoding='utf-8') as json_file:
                data = json.load(json_file)
                header = data[0]['header']
                for item in header:
                    if item['fieldType'] == 'MEASURE':
                        self.measure_dict[item['id']] = True
                    else:
                        self.measure_dict[item['id']] = False
        except Exception as err:
            logger.error("some errors happened in measure_type_recognition initial [{}]: {}".format(type(err), str(err)))
            raise

    def measure_type(self, sel):
        """
        根据sel封装字段，获取类型为measure的header的id
        :param sel:select封装字段
        :return:measure类型的header的id列表
        """
        measure_ids = []
        for item in sel:
            sel_id = item['id']
            if self.measure_dict[sel_id]:
                measure_ids.append(sel_id)
        res = dict()
        res['measure'] = measure_ids
        return res
